package nullInvader.Engine;

import java.awt.Point;
import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Applikationsutveckling i Java, 5DV135 HT12 Project
 * 
 * File: UnitManager.java Description: This class controls the units currently in
 * play and initiates gameStatus checks
 * 
 * Date: 17 december 2012
 * 
 * cs-user: dv11flh
 * 
 * @author Fredrik Loch
 */
public class UnitManager {

    //
    // Fields
    //

    protected List<Unit> unitList;
    protected Player player;
    protected int numGoalUnits;
    protected ArrayList<Point> goalPoint;

    //
    // Constructors
    //

    public UnitManager(ArrayList<Point> arrayList, Player player) {
	goalPoint = arrayList;
	this.player = player;
	numGoalUnits = 0;
	unitList = new CopyOnWriteArrayList<Unit>();
    }

    public UnitManager(ArrayList<Point> arrayList, Player player, List<Unit> u) {
	goalPoint = arrayList;
	this.player = player;
	numGoalUnits = 0;
	unitList = u;
    }

    //
    // Methods
    //

    /**
     * Method to add unit to the unitList
     * 
     * @return boolean
     * @param unit
     */
    public boolean addUnit(Unit unit) {
	return unitList.add(unit);
    }

    /**
     * method responsible for moving the units currently in play also checks
     * game status
     */
    public void tick() throws EmptyStackException {
	for (Unit u : unitList) {
	    if (!u.isDead()) {
		try {
		    u.move();
		} catch (EmptyStackException ex) {
		    if (goalPoint.contains(u.getPosition())) {
			numGoalUnits++;
			unitList.remove(u);
		    } else {
			throw ex;
		    }
		}
		if (goalPoint.contains(u.getPosition())) {
		    numGoalUnits++;
		    u.kill();
		    unitList.remove(u);
		}
	    } else {
		u.kill();
		unitList.remove(u);
	    }
	}
	player.checkGameStatus(numGoalUnits, unitList.size());
    }

}
